<?php
/**
 * Created by PhpStorm.
 * User: colin
 * Date: 15-4-1
 * Time: 21:24
 */

namespace common\entities;

use yii\db\ActiveRecord;
use yii\db\Exception;
use Yii;

class BaseEntity extends ActiveRecord
{
    use \common\error\ReturnErrorTrait;

    public function beforeSave($insert){

        //控制台没有user，不需要维护创建人、修改人
        if(Yii::$app && Yii::$app->id == 'app-console'){
            return parent::beforeSave($insert);
        }

        if(!$this->validate()){
            throw new Exception(self::tableName().":".implode("\n",$this->getFirstErrors()));
        }

        if ($this->isNewRecord) {
            // 自动生成创建人、修改人
            $schema = static::getTableSchema();
            if (!Yii::$app->user->isGuest) {
                $column = $schema->getColumn('created_by');
                if (isset($column) && empty($this->created_by)) {
                    $this->created_by = Yii::$app->user->identity->username;
                }
                
                $column = $schema->getColumn('modified_by');
                if (isset($column) && empty($this->modified_by)) {
                    $this->modified_by = Yii::$app->user->identity->username;
                }
                $column = $schema->getColumn('operator_name');
                if (isset($column) && empty($this->operator_name)) {
                    $this->operator_name = Yii::$app->user->identity->username;
                }

                $column = $schema->getColumn('operator_guid');
                if (isset($column) && empty($this->operator_guid)) {
                    $this->operator_guid = Yii::$app->user->identity->userguid;
                }
            }
        } else {
            $schema = static::getTableSchema();
            if (!Yii::$app->user->isGuest) {
                $column = $schema->getColumn('modified_by');
                if (isset($column) && empty($this->modified_by)) {
                    $this->modified_by = Yii::$app->user->identity->username;
                }
            }
        }
        
        return parent::beforeSave($insert);
    }
}